package com.xxx.common.utils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import com.xxx.common.dto.FileInfo;
import com.xxx.config.WebConfig;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.Thumbnails.Builder;
import net.coobird.thumbnailator.geometry.Positions;

public class FileUtil {
	
	/**
	 * 文件上传
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public final static FileInfo fileUpload(MultipartFile file) throws Exception {
		File targetFile = upload(file);
		FileInfo fileInfo = new FileInfo(targetFile.getName(), file.getSize(), file.getOriginalFilename(), getFileExtName(targetFile.getName()), targetFile.getPath());
		return fileInfo;
	}
	
	/**
	 * 文件上传
	 * @param file
	 * @return
	 * @throws Exception
	 */
	private static File upload(MultipartFile file) throws Exception{
		String path = getUploadPath(); // 保存路径
		String sufFix = getFileExtName(file.getOriginalFilename()); // 文件后缀
		String fileName = getNewFileName(sufFix); // 新文件名
		File targetFile = new File(path, fileName);
		if (!targetFile.exists() && !targetFile.getParentFile().exists()) {
			targetFile.getParentFile().mkdirs();
		}
		file.transferTo(targetFile); // 保存文件
		return targetFile;
	} 
	
	/**
	 * 本地下载文件
	 * @param filepath 本地路劲
	 * @param filename 文件名
	 * @return
	 * @throws IOException
	 */
	public final static ResponseEntity<byte[]> getResponseEntity(String filepath,String filename) throws IOException{
		File file = new File(filepath);
		if(!file.exists()){  
			throw new IOException("文件【"+filepath+"】不存在！");  
		}
		//为了解决中文名称乱码问题  
		filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
		HttpHeaders headers = new HttpHeaders();
		headers.setContentDispositionFormData("attachment", filename);   
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
				headers, HttpStatus.CREATED);
	}
	
	/**
	 * 获取文件上传路径
	 * @return
	 */
	public final static String getUploadPath() {
		StringBuffer path = new StringBuffer();
		path.append(getClassPath())
			.append(DateUtil.getTime(System.currentTimeMillis(), DateUtil.DATE_FORMAT_DATE_YYMM))
			.append(File.separator);
		return path.toString();
	}
	
	/**
	 * 获取系统当前路径
	 * @return
	 */
	public final static String getClassPath() {
		return WebConfig.uploadPath;
	}
	
	/**
	 * 新文件名
	 * @param sufFix 文件后缀
	 * @return
	 * @throws Exception
	 */
	private final static String getNewFileName(String sufFix) {
		String dateToLong = DateUtil.getTime(System.currentTimeMillis(), new SimpleDateFormat("MMddHHmmss"));
		Random r = new Random();
		int randonNum = r.nextInt(99999);
		StringBuffer fileName = new StringBuffer();
		fileName.append(dateToLong).append(String.format("%05d", randonNum)).append(sufFix);
		return fileName.toString();
	}

	/**
	 * 获取文件后缀
	 * @param fileName  文件名
	 * @return
	 */
	public final static String getFileExtName(String fileName) {
		if (fileName.indexOf(".") < 0)
			return "";
		return fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
	}
	
	/**
	 * 获取文件大小,带单位
	 * @param filesize 文件大小,以B为单位
	 * @return
	 */
	public final static String getFileSize(long filesize) {
		double length = filesize;
		String[] size = { "B", "KB", "MB", "GB", "TB" };
		int order = 0;
		while (length >= 1024 && order + 1 < size.length) {
			order++;
			length = length / 1024;
		}
		String fileSize = String.format("%.2f%s", length, size[order]);
		return fileSize;
	}
	
	/**
	 * 压缩至指定图片尺寸（例如：横400高300），保持图片不变形，多余部分裁剪掉
	 * @param file 文件
	 * @param width 宽
	 * @param height 高
	 * @return
	 * @throws Exception
	 */
	public final static FileInfo compressUpload(MultipartFile file, int width, int height) throws Exception {
		File fromPic = upload(file);
		BufferedImage image = ImageIO.read(fromPic);  
		Builder<BufferedImage> builder = null;  
		int imageWidth = image.getWidth();  
		int imageHeitht = image.getHeight();  
		//只缩小,不放大
		if (imageHeitht <= height && imageHeitht <= width) {
			height = imageHeitht;
			width = imageWidth;
		}
		if ((float)width / height != (float)imageWidth / imageHeitht) {
			if (imageWidth > imageHeitht) {  
				image = Thumbnails.of(fromPic).height(height).asBufferedImage();  
			}else{  
				image = Thumbnails.of(fromPic).width(width).asBufferedImage();  
			}  
			builder = Thumbnails.of(image).sourceRegion(Positions.CENTER, width, height).size(width, height);  
		} else {  
			//等比
			builder = Thumbnails.of(image).size(width, height);  
		}  
		builder.outputFormat(getFileExtName(fromPic.getName()).replace(".", "")).toFile(fromPic);
		return new FileInfo(fromPic.getName(), file.getSize(), file.getOriginalFilename(), getFileExtName(fromPic.getName()), fromPic.getPath());
	}
	
	public static void write(String filePath, OutputStream out){
		
		File file = new File(filePath);
		if(file==null || !file.exists()){
		}else{
			InputStream in = null;
			try {
				in = new FileInputStream(file);
				int i = 0;
				while(i != -1) {
						i = in.read();
						out.write(i);
				}
			} catch (IOException e) {
				try {
					throw new IOException("写流失败！");
				} catch (IOException e1) {
				}  
			}finally{
				try{
					if(in != null){
						in.close();
					}
					if(out != null){
						out.close();
					}
				}catch (IOException e) {
					
				}
			}
		}
	}

}
